//
//  WJPDFThumbnailGenerator.swift
//  PDFSign
//
//  Created by 李永彬 on 2025/9/22.
//

import UIKit
import PDFKit

class WJPDFThumbnailGenerator {
    
    /// 根据本地PDF文件URL生成缩略图和文件大小
    static func generate(from localURL: URL, thumbnailSize: CGSize, completion: @escaping (UIImage?, Int?) -> Void) {
        
        DispatchQueue.global().async {
            // 1. 获取文件大小
            let fileSize = getFileSize(from: localURL)
            
            // 2. 生成缩略图
            let thumbnail = generateThumbnail(from: localURL, thumbnailSize: thumbnailSize)
            
            DispatchQueue.main.async {
                completion(thumbnail, fileSize)
            }
        }
    }
    
    // MARK: - 私有方法
    
    private static func getFileSize(from url: URL) -> Int? {
        do {
            let attributes = try FileManager.default.attributesOfItem(atPath: url.path)
            if let size = attributes[.size] as? Int64 {
                return Int(size)
            }
        } catch {
            print("获取文件大小失败: \(error.localizedDescription)")
        }
        return nil
    }
    
    private static func generateThumbnail(from url: URL, thumbnailSize: CGSize) -> UIImage? {
        guard let pdfDocument = PDFDocument(url: url),
              let firstPage = pdfDocument.page(at: 0) else {
            print("无法解析PDF文件或PDF没有页面")
            return nil
        }
        
        // 方法1：使用PDFPage的thumbnail方法（最简单，推荐）
        return generateThumbnailMethod1(firstPage: firstPage, thumbnailSize: thumbnailSize)
        
        // 方法2：手动绘制（更可控）
        // return generateThumbnailMethod2(firstPage: firstPage, thumbnailSize: thumbnailSize)
    }
    
    // MARK: - 方法1：使用PDFPage内置的thumbnail方法（推荐）
    private static func generateThumbnailMethod1(firstPage: PDFPage, thumbnailSize: CGSize) -> UIImage? {
        // PDFPage有内置的生成缩略图方法，会自动处理旋转
        let thumbnail = firstPage.thumbnail(of: thumbnailSize, for: .mediaBox)
        return thumbnail
    }
    
    // MARK: - 方法2：手动绘制（如果需要更多控制）
    private static func generateThumbnailMethod2(firstPage: PDFPage, thumbnailSize: CGSize) -> UIImage? {
        // 获取页面边界（考虑旋转）
        let pageBounds = firstPage.bounds(for: .mediaBox)
        
        // 计算合适的缩放比例
        let scale = min(thumbnailSize.width / pageBounds.width,
                       thumbnailSize.height / pageBounds.height)
        
        // 计算最终尺寸
        let renderSize = CGSize(width: pageBounds.width * scale,
                               height: pageBounds.height * scale)
        
        // 创建图像渲染器
        let renderer = UIGraphicsImageRenderer(size: renderSize)
        
        return renderer.image { context in
            // 设置白色背景
            UIColor.white.setFill()
            context.fill(CGRect(origin: .zero, size: renderSize))
            
            // 保存图形状态
            context.cgContext.saveGState()
            
            // 关键修正：应用缩放变换
            context.cgContext.scaleBy(x: scale, y: scale)
            
            // 让PDFPage自己处理旋转，不要手动干预
            firstPage.draw(with: .mediaBox, to: context.cgContext)
            
            // 恢复图形状态
            context.cgContext.restoreGState()
        }
    }
    
    // MARK: - 方法3：高级版本（处理复杂旋转）
    private static func generateThumbnailMethod3(firstPage: PDFPage, thumbnailSize: CGSize) -> UIImage? {
        let pageBounds = firstPage.bounds(for: .mediaBox)
        let rotation = firstPage.rotation
        
        // 根据旋转调整边界
        var adjustedBounds = pageBounds
        if rotation == 90 || rotation == 270 {
            swap(&adjustedBounds.size.width, &adjustedBounds.size.height)
        }
        
        // 计算缩放比例
        let scale = min(thumbnailSize.width / adjustedBounds.width,
                       thumbnailSize.height / adjustedBounds.height)
        
        let renderSize = CGSize(width: adjustedBounds.width * scale,
                               height: adjustedBounds.height * scale)
        
        let renderer = UIGraphicsImageRenderer(size: renderSize)
        
        return renderer.image { context in
            UIColor.white.setFill()
            context.fill(CGRect(origin: .zero, size: renderSize))
            
            context.cgContext.saveGState()
            
            // 应用缩放
            context.cgContext.scaleBy(x: scale, y: scale)
            
            // 根据旋转调整坐标系
            switch rotation {
            case 90:
                context.cgContext.translateBy(x: adjustedBounds.width, y: 0)
                context.cgContext.rotate(by: .pi / 2)
            case 180:
                context.cgContext.translateBy(x: adjustedBounds.width, y: adjustedBounds.height)
                context.cgContext.rotate(by: .pi)
            case 270:
                context.cgContext.translateBy(x: 0, y: adjustedBounds.height)
                context.cgContext.rotate(by: -.pi / 2)
            default:
                break
            }
            
            // 绘制页面
            firstPage.draw(with: .mediaBox, to: context.cgContext)
            context.cgContext.restoreGState()
        }
    }
}
